package com.orion.config;

import cn.hutool.json.JSONUtil;
import com.orion.domain.Result;
import com.orion.enumeration.Oauth2ExceptionCodeEnum;
import com.orion.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Administrator
 * @date 2021/10/11
 */
@Component
@Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler{
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        log.info("resource access deny : " , accessDeniedException);
        Oauth2ExceptionCodeEnum accessDenied = Oauth2ExceptionCodeEnum.ACCESS_DENIED;
        Result result = new Result(accessDenied.getMsg(),accessDenied.getCode());
        ResponseUtil.jsonResp(response).getWriter().write(JSONUtil.toJsonStr(result));
    }
}
